﻿using CMS.Utility;
using DBMode;
using DryIoc;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CMS.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {
        public LoginViewModel(IMethods<Member> memberMethods)
        {
            this.memberMethods = memberMethods;
        }
        public string Title { get; set; }

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
           
        }

        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set { selectedIndex = value;RaisePropertyChanged(); }
        }

        public DelegateCommand<string> ExcuteCommand { get { return new DelegateCommand<string>(Excute); } }

        private void Excute(string obj)
        {
            switch (obj) {
                case "Register": SelectedIndex=1; break;
                case "Goback": SelectedIndex=0; break;
                case "Confirm": Register(); break;
                case "Login": Login(); break;
  
            }
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Login()
        {
            if (Member.Name == null || Member.Password == null) return;
            else
            {
                var mode = memberMethods.Query().FirstOrDefault(i => (i.Name == Member.Name) && i.Password == Member.Password.EnMD5());
                if (mode == null) return;
                RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            }
        }

        public Member Member { get; set; } = AppInstance.GetInstance.Member;
        private readonly IMethods<Member> memberMethods;
        /// <summary>
        /// 注册
        /// </summary>
        private void Register()
        {
            if (string.IsNullOrEmpty(Member.Name) || string.IsNullOrEmpty(Member.Password) || (Member.Role) == null) return;
            Member.Password = Member.Password.EnMD5();
            int i= memberMethods.Add(Member);

            if (i == 0) MessageBox.Show("添加错误");
            else
                MessageBox.Show("添加成功");
        }
    }
}
